package models

import (
	"hsy/config"

	"github.com/jinzhu/gorm"
)

// UserModel 用户model
type UserModel struct {
	config.Model
	Name     string `gorm:"column:name;not nul;index:name_idx" json:"name"`
	Sex      int    `gorm:"column:sex;not null" json:"sex"` // 0 男  1 女
	Username string `gorm:"column:username;unique_index;not null" json:"username"`
	Password string `gorm:"column:password;not null" json:"password,omitempty"`
	Token    string `gorm:"column:token" json:"token,omitempty"`
}

// ListResponse 列表返回
type ListResponse struct {
	Total int         `json:"total"`
	List  []UserModel `json:"list"`
}

var self *gorm.DB

func init() {
	self = config.Self
	self.AutoMigrate(&UserModel{})
}


// TableName 用户表名
func (u *UserModel) TableName() string {
	return "users"
}

// CheckUsernameExist 查看用户是否存在
func (u *UserModel) CheckUsernameExist(username string) bool {
	var user UserModel
	if self.Where("username = ?", username).First(&user).RecordNotFound() {
		return false
	}
	return true
}

// CheckExceptSelf 查看用户是否存在排除自己
func (u *UserModel) CheckExceptSelf(username string, id int) bool {
	var user UserModel
	if self.Where("username = ?", username).Not("id = ?", id).First(&user).RecordNotFound() {
		return false
	}
	return true
}

// GetOne 查询一个用户
func (u *UserModel) GetOne(username string) (interface{}, bool) {
	var user UserModel
	row := self.Where("username = ?", username).First(&user)
	if row.RecordNotFound() {
		return nil, false
	}
	return user, true
}

// Create 创建用户
func (u *UserModel) Create() error {
	return self.Create(&u).Error
}

// Update 更新用户信息
func (u *UserModel) Update(id int) error {
	var user UserModel
	return self.Model(&user).Where("id = ?", id).Updates(&u).Error
}

// Delete 删除用户
func (u *UserModel) Delete(id int) error {
	return self.Where("id = ?", id).Delete(&u).Error
}
